package some

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"

	"gitee.com/thubcc/p2pgit/classedpack"
	"gitee.com/thubcc/p2pgit/types"
)

var (
	idxSuffix       = ".nidx"
	packSuffix      = ".npack"
	examplePack     = "np-08-0000000000000003" + packSuffix
	packFileNameLen = len(examplePack)
)

// Geter2Hashes get all hash
func Geter2Hashes(gs types.SomeGeter) (hs []types.Hash) {
	for _, v := range gs {
		if cpf, ok := v.(*classedpack.File); ok {
			ihs, err := cpf.Hashes()
			if err == nil {
				hs = append(hs, ihs...)
			} else {
				fmt.Println(cpf.C.String(), ":", err)
			}
		}
	}
	return
}

// GeterFromDir get all pack file in a special dir
func GeterFromDir(dir string) (gs types.SomeGeter, err error) {
	var rd []os.FileInfo
	rd, err = ioutil.ReadDir(dir)
	if err != nil {
		return
	}
	for _, fi := range rd {
		if !fi.IsDir() {
			base := fi.Name()
			if classedpack.CheckPackFileName(base) == nil {
				full := path.Join(dir, base)
				var cpf types.Geter
				cpf, err = classedpack.NewFile(full)
				if err != nil {
					return
				}
				gs = append(gs, cpf)
			}
		}
	}
	return
}

// GeterFromServer get all api from server
func GeterFromServer(url string) (gs types.SomeGeter, err error) {
	var resp *http.Response
	resp, err = http.Get(url + "/api")
	if err != nil {
		return
	}
	defer resp.Body.Close()
	dec := json.NewDecoder(resp.Body)
	var apis []string
	err = dec.Decode(&apis)
	if err != nil && err != io.EOF {
		return
	}
	for _, api := range apis {
		if classedpack.CheckAPIName(api) == nil {
			var cpc types.Geter
			cpc, err = classedpack.NewBasicAPI(url, api)
			if err != nil {
				return
			}
			gs = append(gs, cpc)
		}
	}
	return
}
